<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分类" prop="classify_id">
        <el-select v-model="queryParams.classify_id" placeholder="请选择分类" clearable style="width: 240px">
          <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="goodsList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="商品名称" prop="name" min-width="200" show-overflow-tooltip />
      <el-table-column label="分类" prop="classify_id" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ getCategoryName(scope.row.classify_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" prop="type" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" prop="owner_id" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ getOwnerName(scope.row.owner_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" min-width="200" align="center">
        <template slot-scope="scope">
          <div v-if="getImageList(scope.row.images) && getImageList(scope.row.images).length" class="image-preview">
            <el-image v-for="(img, index) in getImageList(scope.row.images).slice(0, 3)" :key="img + index"
              :src="getImageUrl(img)" :preview-src-list="getImageList(scope.row.images).map(img => getImageUrl(img))"
              fit="cover" class="image-preview__item" />
            <span v-if="getImageList(scope.row.images).length > 3" class="image-preview__more">+{{
              getImageList(scope.row.images).length - 3 }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="tag" width="150" align="center">
        <template slot-scope="scope">
          <el-tag v-for="(tag, index) in (Array.isArray(scope.row.tag) ? scope.row.tag : [])" :key="index" size="mini"
            style="margin-right: 5px;">{{ tag }}</el-tag>
          <span v-if="!scope.row.tag || !scope.row.tag.length">-</span>
        </template>
      </el-table-column>
      <el-table-column label="是否热销" prop="is_hot" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_hot ? 'success' : 'info'">{{ scope.row.is_hot ? '是' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at ? parseTime(scope.row.created_at) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="classify_id">
          <el-select v-model="form.classify_id" placeholder="请选择分类" clearable style="width: 100%">
            <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label"
              :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-input-number v-model="form.type" :min="0" placeholder="请输入商品类型" style="width: 100%" />
        </el-form-item>
        <el-form-item label="负责人" prop="owner_id">
          <el-select v-model="form.owner_id" placeholder="请选择负责人" clearable filterable style="width: 100%">
            <el-option v-for="option in ownerOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <el-input v-model="form.detail" type="textarea" :rows="4" placeholder="请输入商品详情" />
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <image-upload v-model="form.image" :limit="10" :file-size="5" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-select v-model="form.tag" multiple filterable allow-create default-first-option placeholder="请输入或选择标签"
            style="width: 100%">
            <el-option v-for="tag in form.tag" :key="tag" :label="tag" :value="tag" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否热销" prop="is_hot">
          <el-radio-group v-model="form.is_hot">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="option in statusOptions" :key="option.value" :label="option.value">{{ option.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsList, addGoods, updateGoods, getCategoryList, getUserList } from '@/api/api'
import ImageUpload from '@/components/ImageUpload'

export default {
  name: 'Goods',
  components: { ImageUpload },
  data() {
    return {
      loading: false,
      submitLoading: false,
      showSearch: true,
      goodsList: [],
      categoryOptions: [],
      ownerOptions: [],
      categoryMap: {},
      ownerMap: {},
      statusOptions: [
        { label: '上架', value: 1 },
        { label: '下架', value: 2 }
      ],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      open: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      queryParams: {
        page: 1,
        pageSize: 10,
        name: undefined,
        classify_id: undefined,
        status: undefined
      },
      form: {
        id: undefined,
        name: '',
        classify_id: undefined,
        type: 0,
        owner_id: undefined,
        detail: '',
        image: [],
        tag: [],
        is_hot: false,
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度需在 1 到 100 个字符', trigger: 'blur' }
        ],
        classify_id: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getCategoryOptions()
    this.getOwnerOptions()
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      getGoodsList(this.queryParams)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.goodsList = list
          this.total = total || list.length
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    getCategoryOptions() {
      getCategoryList({})
        .then(res => {
          const { list } = this.normalizeResponse(res)
          const flattenCategories = this.flattenCategories(list)
          this.categoryOptions = flattenCategories.map(item => ({
            label: item.name,
            value: item.id
          }))
          this.categoryMap = {}
          flattenCategories.forEach(item => {
            this.categoryMap[item.id] = item.name
          })
        })
    },
    flattenCategories(list = [], result = []) {
      list.forEach(item => {
        result.push(item)
        if (Array.isArray(item.children) && item.children.length) {
          this.flattenCategories(item.children, result)
        }
      })
      return result
    },
    getOwnerOptions() {
      getUserList({})
        .then(res => {
          const { list } = this.normalizeResponse(res)
          this.ownerOptions = list.map(item => ({
            label: item.name || item.username || `用户${item.id}`,
            value: item.id
          }))
          this.ownerMap = {}
          list.forEach(item => {
            this.ownerMap[item.id] = item.name || item.username || `用户${item.id}`
          })
        })
    },
    getCategoryName(id) {
      return this.categoryMap[id] || '-'
    },
    getOwnerName(id) {
      return this.ownerMap[id] || '-'
    },
    getImageList(image) {
      if (!image) return []
      if (Array.isArray(image)) {
        return image.filter(Boolean)
      }
      if (typeof image === 'string' && image) {
        return image.split(',').filter(Boolean)
      }
      return []
    },
    getImageUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) {
        return url
      }
      if (this.baseUrl && url.startsWith(this.baseUrl)) {
        return url
      }
      if (this.baseUrl) {
        const prefix = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl
        const path = url.startsWith('/') ? url : `/${url}`
        return `${prefix}${path}`
      }
      return url
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    reset() {
      this.form = {
        id: undefined,
        name: '',
        classify_id: undefined,
        type: 0,
        owner_id: undefined,
        detail: '',
        image: '', // ImageUpload 组件需要字符串格式
        tag: [],
        is_hot: false,
        status: 1
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增商品'
    },
    handleUpdate(row) {
      const targetId = row?.id ?? this.ids[0]
      if (!targetId) {
        this.$modal.msgWarning('请选择要修改的商品')
        return
      }
      const record = this.goodsList.find(item => String(item.id) === String(targetId))
      if (!record) {
        this.$modal.msgWarning('未找到对应的商品数据')
        return
      }
      // 处理图片格式（后端返回的是 images）
      let imageValue = []
      if (Array.isArray(record.images)) {
        imageValue = record.images.filter(Boolean)
      } else if (typeof record.images === 'string' && record.images) {
        imageValue = record.images.split(',').filter(Boolean)
      }
      // 兼容旧的 image 字段
      if (imageValue.length === 0 && Array.isArray(record.image)) {
        imageValue = record.image.filter(Boolean)
      } else if (imageValue.length === 0 && typeof record.image === 'string' && record.image) {
        imageValue = record.image.split(',').filter(Boolean)
      }

      // 处理标签格式
      let tagValue = []
      if (Array.isArray(record.tag)) {
        tagValue = record.tag.filter(Boolean)
      } else if (typeof record.tag === 'string' && record.tag) {
        tagValue = record.tag.split(',').filter(Boolean)
      }

      this.form = {
        id: record.id,
        name: record.name || '',
        classify_id: record.classify_id,
        type: record.type || 0,
        owner_id: record.owner_id,
        detail: record.detail || '',
        image: imageValue.length > 0 ? imageValue.join(',') : '', // ImageUpload 组件需要字符串格式
        tag: tagValue,
        is_hot: record.is_hot || false,
        status: record.status || 1
      }
      this.$nextTick(() => {
        if (this.$refs.form && this.$refs.form.clearValidate) {
          this.$refs.form.clearValidate()
        }
      })
      this.open = true
      this.title = '修改商品'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        this.submitLoading = true
        const payload = {
          ...this.form
        }

        // 处理图片格式：确保是数组格式，接口参数使用 image
        if (typeof payload.image === 'string' && payload.image) {
          payload.image = payload.image.split(',').filter(Boolean)
        } else if (Array.isArray(payload.image)) {
          payload.image = payload.image.filter(Boolean)
        } else {
          payload.image = []
        }
        // 删除 images 字段（如果存在），统一使用 image 提交
        delete payload.images

        // 处理标签格式：确保是数组格式
        if (typeof payload.tag === 'string' && payload.tag) {
          payload.tag = payload.tag.split(',').filter(Boolean)
        } else if (!Array.isArray(payload.tag)) {
          payload.tag = []
        }
        const request = payload.id ? updateGoods(payload) : addGoods({ ...payload, id: undefined })
        request
          .then(() => {
            this.$modal.msgSuccess(payload.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = selection.length === 0
    },
    getStatusLabel(value) {
      const target = this.statusOptions.find(item => Number(item.value) === Number(value))
      return target ? target.label : '-'
    },
    getStatusTagType(value) {
      const match = Number(value)
      if (match === 1) {
        return 'success'
      }
      if (match === 2) {
        return 'danger'
      }
      return 'default'
    }
  }
}
</script>

<style scoped lang="scss">
.image-preview {
  display: flex;
  align-items: center;
}

.image-preview__item {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 6px;
}

.image-preview__more {
  font-size: 12px;
  color: #909399;
}
</style>
